package LeetCode.leetcode102;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> res = new ArrayList<>();
        TreeNode node;

        //如果root为空直接返回
        if (root == null)
            return res;
        //添加第一个
        queue.offer(root);
        while (!queue.isEmpty()){
            List<Integer> lines = new ArrayList<>();
            int length = queue.size();
            while (length > 0){
                node = queue.poll();
                assert node != null;
                lines.add(node.val);
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);
                length--;
            }
            //添加每一层的元素
            res.add(lines);
        }
        return res;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public List<List<Integer>> levelOrder2(TreeNode root){
        List<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null)
            return res;
        //添加第一个节点
        queue.offer(root);
        TreeNode node;
        while (!queue.isEmpty()){
            List<Integer> lines = new ArrayList<>();
            int size = queue.size();
            while (size-- > 0){
                node = queue.poll();
                assert node != null;
                lines.add(node.val);
                if (node.left != null)
                    queue.offer(node.left);
                if (node.right != null)
                    queue.offer(node.right);
            }
            res.add(lines);
        }
        return res;
    }
}
